<?php
declare (strict_types = 1);

namespace app\api\provider;

use app\common\libs\Jwt;
use app\common\libs\Singleton;
use app\Request;
use think\App;

class Userinfo
{
    use Singleton;

    public $id = 0;

    public $phone = '';

    public $username = '';

    //是否登陆
    public function isLogin(): bool
    {
        return $this->id > 0;
    }

    /**
     * 登录信息设置
     * @param Request $request
     */
    public function setLoginInfo(Request $request)
    {
        $token = $request->header('token', '');
        if (empty($token)) {
            $token = input('token');
        }

        $payload = Jwt::verifyToken($token);
        if (false === $payload || ! is_array($payload)) {
            return;
        }
        /*$loginDate = date('Ymd', $payload['loginTime']);
        if ($loginDate != date('Ymd')) {
            return;
        }*/
        // var_dump($payload);exit;
        foreach ($payload as $k => $v) {
            App::getInstance()->userinfo->{$k} = $v;
        }
    }

    public function match($arr = [], Request $request): bool
    {
        $arr = is_array($arr) ? $arr : explode(',', $arr);
        if ( ! $arr) {
            return false;
        }
        $arr = array_map('strtolower', $arr);
        // 是否存在
        if (in_array(strtolower($request->action()), $arr) || in_array('*', $arr)) {
            return true;
        }

        // 没找到匹配
        return false;
    }
}
